mardi 19 janvier 2021

Why can't I statically initialize this?

I have following code which try to get the connection URL using environment variables then init the mongo URL object. It compiles but when I run it, it instantly throw an error that invalid URL was used. The function getEnvVar not getting called at all.

#include <iostream>
#include <chrono>
#include <cstdint>
#include <sstream>
#include <iomanip>
#include <string>
#include <array>
#include <vector>
#include <stdexcept>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/instance.hpp>

using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::open_document;

std::string getEnvVar(std::string const& key)
{
    char const* val = getenv(key.c_str()); 

    std::cout << val << "\n";

    if(val == NULL) {
        std::cout << "EMPTY ENV VAR" << "\n";
    }

    return val == NULL ? std::string() : std::string(val);
}

// Connect to Database
mongocxx::instance instance{};

mongocxx::uri uri(getEnvVar("DatabaseURI"));
mongocxx::client client(uri);

int main() {
    std::cout << "Started" << "\n";
}

Here is the stack-trace from valgrind,

terminate called after throwing an instance of 'mongocxx::v_noabi::logic_error'
  what():  an invalid MongoDB URI was provided
==441535==
==441535== Process terminating with default action of signal 6 (SIGABRT)
==441535==    at 0x4FCF18B: raise (raise.c:51)
==441535==    by 0x4FAE858: abort (abort.c:79)
==441535==    by 0x4E29950: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28)
==441535==    by 0x4E3547B: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28)
==441535==    by 0x4E354E6: std::terminate() (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28)
==441535==    by 0x4E35798: __cxa_throw (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28)
==441535==    by 0x4CF7631: mongocxx::v_noabi::uri::uri(bsoncxx::v_noabi::string::view_or_value) [clone .cold] (in /usr/local/lib/libmongocxx.so.0.0.0)
==441535==    by 0x122272: __static_initialization_and_destruction_0(int, int) [clone .constprop.0] (in /home/app)
==441535==    by 0x19917C: __libc_csu_init (in /home/app)
==441535==    by 0x4FB003F: (below main) (libc-start.c:264)

Aucun commentaire:

Enregistrer un commentaire