CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jul 2009
    Posts
    9

    Exclamation Convert Reference To Pointer ?

    hi how can i convert a refence to a poiner ?

    here is the method :

    void Foo(const std::string& s,...)
    {
    const std::string* a = s ; //here we will do the conversion.

    va_list args;
    va_start(args,a);

    //methodV(args);
    va_end(args);
    }


    I tried the following but none of these works :

    1) const std::string* a = s ;


    error C2440: 'initializing' : cannot convert from std::string' to 'const std::string *'
    No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called.

    2) const std::string* a = &s ;

    compiles, but when run "args" has random junk values
    e.g an int passed has value 12300000 instead of 1000.

    3) const std::string* a = *s ;

    error C2100: illegal indirection


    Here what i have done and works, but i am forced to use pointer.

    1) int Foo(const std::string* s,...);

    OK but user has to call it this way : Foo( &string("MYSTRING") , 1000 )
    Which is complecated but works.

    2) int Foo(const std::String s,...);

    OK but it is slow, user has to wait for the string to get copy constructed.


    so is there a workaround ?

    thank you for your patience,

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Convert Reference To Pointer ?

    Variadic arguments simply don't mix well with C++ concepts such as references. You also can't pass non-primitive types through them, FYI.

    If you need to use a va_list, I would suggest passing the string as a const char*. If one bit of the function is C, keep it all C; mixing C-only and C++ concepts tends to break things.

  3. #3
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Convert Reference To Pointer ?

    Code:
    void Foo(const std::string& s,...)
    First thing (and most important).

    The ANSI C++ specification (section 18.7.3) states that the first argument in a variable argument lists cannot be a reference. Doing so is undefined behaviour.

    So if you're trying to pass a reference in a function that takes a variable argument list, forget about it.

    Regards,

    Paul McKenzie

  4. #4
    Join Date
    Jul 2009
    Posts
    9

    Re: Convert Reference To Pointer ?

    ok then, i will pass parameters by pointer.

    thanks for your help,

Tags for this Thread

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