开发者

Need help for C++ boost::optional

开发者 https://www.devze.com 2023-02-06 04:47 出处:网络
#include </usr/include/boost/optional.hpp> #include <iostream> using namespace std; boost::optional<int> test_func(int i)
#include </usr/include/boost/optional.hpp>  
#include <iostream>
using namespace std;


boost::optional<int> test_func(int i)
{    
  if(i)   
    return boost::optional<int>(1234);
  else   
    return boost::optional<int>();
  return (i);   
}

int main()
{
  int i;
  test_func(1234);
  std::cout<< test_func(i) << endl;
  return 0;
}

Could any body please tell me y am i getting the value of i as 0, what i want to do is i want to print the values of " i " after entering into " if " condition & also in the " else" part.

Please do the needful, refer m开发者_高级运维e any modification's Thanks Arun.D

Help is greatly appreciated.. thanks in advance


int i has not been explicitly initialised. If i == 0 then nil (default boost::optional) is returned, when you print you will get 0.


You haven't initialized i. The behavior of this program is undefined. Set it to a non-zero value explicitly.


In main() you haven't initialized i. And in test_func() you will never reach return (i);.


Other have already commented: you are using i without initializing and it is default initialized to 0. But maybe you are wondering why you don't see 1234: this is because you are discarding the return value (hard-coded to boost::optional(1234) ). Maybe you meant to write

std::cout << *test_func(1234) << endl; // by using operator* you are not discarding the return value any more
std::cout<< test_func(i) << endl;

Read the documentation and look at the examples for more information


Besides the unitialized i and not reaching return i; other already mentioned:

You are printing the bool conversion of boost::optional. When the optional contains a value it prints 1, when the optional does not contain a value it prints 0.

I think you mean something like:

boost::optional<int> result(test_func(i));
if (result)
{
    std::cout << *result;
}
else
{
    std::cout << "*not set*";
}

and not

std::cout << test_func(i);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号