CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    John E is offline Elite Member Power Poster
    Join Date
    Apr 2001
    Location
    Manchester, England
    Posts
    4,835

    :: operator new()

    I just came across this code in a template class:-

    Code:
    	pointer allocate (size_type n, void* hint = 0)
    	{
    		if ((pointer)&_buf + stack_capacity >= _ptr + n) {
    			pointer rv = _ptr;
    			_ptr += n;
    			return rv;
    		} else {
    			return static_cast<pointer> (::operator new (n * sizeof (T)));
    		}
    	}
    I just wondered what's the significance of :: operator in front of the call to new()
    "A problem well stated is a problem half solved.” - Charles F. Kettering

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: :: operator new()

    :: usually means global. Just to distinguish from the possible local definition of the same operator or method in a class.
    Victor Nijegorodov

  3. #3
    Join Date
    May 2001
    Location
    Germany
    Posts
    1,158

    Re: :: operator new()

    https://en.cppreference.com/w/cpp/me...w/operator_new
    section "Class-specific overloads":
    "If defined, these allocation functions are called by new-expressions to allocate memory for single objects and arrays of this class, unless the new expression used the form ::new which bypasses class-scope lookup."

  4. #4
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: :: operator new()

    Code:
    return static_cast<pointer> (::operator new (n * sizeof (T)));
    operator new (<size>) allocates memory and returns a type void* but does not call any constructor. :: just means the global namespace version.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured