-1

When I pass a string literal to a dynamically allocated unique_ptr and then store in vector (using std::move since there's apparently no other way), I get an odd return value when the string is fetched - it appears to have been cut/moved.

#include <iostream>
#include <vector>
#include <memory>

class Something {
private:
    const char* name;
public:
    Something(const char* name) {
        this->name = name;
    }

    void printDetails() {
        std::cout << this->name << std::endl;
    }
};

int main()
{
    std::vector<std::unique_ptr<Something>> stuff;

    for(int i = 0; i < 10; i++) {
        std::unique_ptr<Something> thing(new Something("A nice fun string" + i));
        stuff.push_back(std::move(thing));
    }

    for(uint i = 0; i < stuff.size(); i++) {
        stuff[i]->printDetails();
    }

    return 0;
}

Output:

A nice fun string
 nice fun string
nice fun string
ice fun string
ce fun string
e fun string
 fun string
fun string
un string
n string
user3530525
  • 691
  • 3
  • 8
  • 20

2 Answers2

3

It's not moved. "ABC" is string literal, and actually is just a pointer char const *. Adding integer just moves it forward, so "ABC" + 1 acts like "BC".

C-style string literals are just char arrays, and arrays, when you access their contents, are just pointers to their first element. So adding integer th this pointer will work as suffix of your array.

What you want is probably concat your literal and integer, it's not so easy in C++. The fastest approach using C++11 looks terrible:

string("ABC") + to_string(i)

And, if you really want char * in the end, copy the resulting string of that (it's well described here)

(string("ABC") + to_string(i)).c_str()
Community
  • 1
  • 1
Lapshin Dmitry
  • 1,084
  • 9
  • 28
3

This part causes the error:

("A nice fun string" + i) 

i must be a char or a char* itself, you are increasing the index of "A nice fun string" by i.

b.holz
  • 237
  • 3
  • 17